﻿using System.Collections.Generic;
using CoreEx.Common.Mediator;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;

namespace CoreEx.Common.Implementation.Mediator
{
    /// <summary>
    /// A <see cref="IFactory{T}"/> instance that creates <see cref="IMediator"/> instances.
    /// </summary>
    /// <remarks>
    /// A <see cref="IMediator"/> instance is considered a singleton within the scope of its name.
    /// </remarks>
    [Factory(typeof(IMediator))]
    public class MediatorFactory : IFactory<IMediator>
    {
        private static readonly IDictionary<string, IMediator> _mediators = 
            new Dictionary<string, IMediator>();
        
        public IMediator CreateInstance(IFactoryRequest request)
        {
            lock (request)
            {
                var serviceName = request.ServiceName ?? string.Empty;
                if (!_mediators.ContainsKey(serviceName))
                    _mediators.Add(serviceName,new Mediator());                
                return _mediators[serviceName];                
            }
        }
    }
}
